<template>
    <div class="container">
        <el-form
            ref="form"
            v-loading="isLoading"
            :model="bookInfo"
            label-width="5rem"
            :rules="rules"
            element-loading-text="表单加载中..."
        >
            <el-form-item label="标题" prop="title">
                <el-input v-model="bookInfo.title" placeholder="请输入标题" clearable />
            </el-form-item>
            <el-form-item label="作者" prop="author">
                <el-input v-model="bookInfo.author" placeholder="请输入作者" clearable />
            </el-form-item>
            <el-form-item label="ISBN" prop="isbn">
                <el-input v-model="bookInfo.isbn" placeholder="请输入ISBN" clearable />
            </el-form-item>
            <el-form-item label="分类" prop="categoryID">
                <el-select v-model="bookInfo.categoryID" placeholder="请选择分类" filterable>
                    <el-option
                        v-for="item in categoryList"
                        :key="item.categoryID"
                        :label="item.category"
                        :value="item.categoryID"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="语言" prop="language">
                <el-select v-model="bookInfo.language" placeholder="请选择语言" filterable>
                    <el-option v-for="item in languageList" :key="item" :value="item"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="简介" prop="summary">
                <el-input v-model="bookInfo.summary" type="textarea" resize="none" rows="5" />
            </el-form-item>
            <el-form-item class="image">
                <el-upload
                    class="upload"
                    ref="upload"
                    :auto-upload="true"
                    drag
                    action="http://localhost:8088/bookmall/book/upload"
                    name="file"
                    :limit="1"
                    :on-progress="progressHandler"
                    :on-success="successHandler"
                    :on-remove="removeHandler"
                    :on-change="changeHandler"
                    :on-error="errorHandler"
                    accept=".jpg,.jpeg"
                    list-type="image"
                >
                    <el-icon size="4rem"><Plus /></el-icon>
                    <div class="el-upload__text">拖拽文件至此 或者 <em>点击上传</em></div>
                    <template #tip>
                        <div class="el-upload__tip">文件格式应为JPEG，且大小不得超过1Mb</div>
                    </template>
                </el-upload>
                <div>
                    <el-image :src="bookInfo.coverImg"></el-image>
                </div>
            </el-form-item>
            <el-form-item label="出版时间" prop="pubDate">
                <el-date-picker v-model="form.pubDate" type="month" placeholder="请选择出版时间" />
            </el-form-item>
            <el-form-item label="出版社" prop="publisher">
                <el-input v-model="form.publisher" placeholder="请输入出版社" />
            </el-form-item>
            <el-form-item label="售价" prop="price">
                <el-input-number :min="1" :precision="2" v-model="form.price" placeholder="请输入价格" />
            </el-form-item>
            <el-form-item label="库存数量" prop="stockNum">
                <el-input-number :min="0" v-model="form.stockNum" placeholder="请输入库存数量" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitUpdate">保存</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
// import api from "@/api";
import { Plus } from "@element-plus/icons-vue";
import service from "@/utils/request";
import { ElNotification } from "element-plus";
import { userStore } from "@/store/user";

export default {
    props: ["form"],
    components: { Plus },
    async beforeMount() {
        this.isLoading = true;
        if (this.form !== null) {
            this.bookInfo = this.form;
            // console.log(this.bookInfo);
        }
        service.get("/category/list").then((res) => {
            this.categoryList = res.data.data;
        });
        this.isLoading = false;
    },
    data() {
        return {
            isLoading: true,
            bookInfo: {
                bookID: 0,
                title: "",
                author: "",
                isbn: "",
                category: "",
                coverImg: "",
                pubDate: "",
                publisher: "",
                summary: "",
                language: "",
                soldNum: 0,
                stockNum: "",
                price: "",
            },
            categoryList: [],
            languageList: [
                "简体中文",
                "繁体中文",
                "英语",
                "日语",
                "俄语",
                "法语",
                "德语",
                "西班牙语",
                "葡萄牙语",
                "其他",
            ],
            rules: {
                pubDate: {
                    required: true,
                    validator: (rule, value, callback) => {
                        if (value === "") {
                            callback(new Error("请选择出版日期"));
                        } else {
                            callback();
                        }
                    },
                    trigger: "change",
                },
                publisher: {
                    required: true,
                    validator: (rule, value, callback) => {
                        if (value === "") {
                            callback(new Error("请输入出版社"));
                        } else {
                            callback();
                        }
                    },
                    trigger: "change",
                },
                price: {
                    required: true,
                },
                stockNum: {
                    required: true,
                },
                title: {
                    required: true,
                    validator: (rule, value, callback) => {
                        if (value === "") {
                            callback(new Error("标题不能为空"));
                        } else {
                            callback();
                        }
                    },
                    trigger: "blur",
                },
                author: {
                    required: true,
                    validator: (rule, value, callback) => {
                        if (value === "") {
                            callback(new Error("作者不能为空"));
                        } else {
                            callback();
                        }
                    },
                    trigger: "blur",
                },
                isbn: {
                    validator: (rule, value, callback) => {
                        if (!value.match(/[0-9]{13}/) && value.length !== 0) {
                            callback(new Error("ISBN需为13位数字"));
                        } else {
                            callback();
                        }
                    },
                    length: 13,
                    trigger: "change",
                },
                categoryID: {
                    required: true,
                    validator: (rule, value, callback) => {
                        if (value === "") {
                            callback(new Error("请选择图书分类"));
                        } else {
                            callback();
                        }
                    },
                    trigger: "change",
                },
                language: {
                    required: true,
                    validator: (rule, value, callback) => {
                        if (value === "") {
                            callback(new Error("请选择语言"));
                        } else {
                            callback();
                        }
                    },
                    trigger: "change",
                },
                summary: {
                    required: true,
                    validator: (rule, value, callback) => {
                        if (value === "") {
                            callback(new Error("请输入简介"));
                        } else if (value.length < 10 || value.length > 500) {
                            callback(new Error("简介字数需在10-500字之间"));
                        } else {
                            callback();
                        }
                    },
                    min: 10,
                    max: 500,
                    trigger: "blur",
                },
            },
        };
    },
    methods: {
        removeHandler() {
            this.isDisabled = true;
        },
        progressHandler(file) {
            // console.log(file);
            if (file.total > 1024 * 1024 * 1) {
                this.$refs["upload"].abort();
                return;
            }
            service.post(`/book/deleteFromOSSById/${this.bookInfo.bookID}`);
        },
        changeHandler() {
            this.isDisabled = true;
        },
        successHandler(res) {
            this.bookInfo.coverImg = res.data;
            // console.log(res);
        },
        errorHandler() {
            this.isDisabled = true;
            ElMessage({
                type: "error",
                message: "上传文件大小不得超过1Mb",
            });
        },
        submitUpdate() {
            this.$refs["form"].validate(async (valid) => {
                if (typeof this.bookInfo.pubDate !== "string")
                    this.bookInfo.pubDate =
                        this.bookInfo.pubDate.getFullYear() +
                        "-" +
                        (this.bookInfo.pubDate.getMonth() + 1 < 10
                            ? "0" + (this.bookInfo.pubDate.getMonth() + 1).toString()
                            : (this.bookInfo.pubDate.getMonth() + 1).toString());
                if (valid) {
                    this.isLoading = true;
                    await service({
                        method: "patch",
                        url: "/book/update",
                        headers: {
                            "Content-Type": "application/json",
                        },
                        data: this.bookInfo,
                    })
                        .then(() => {
                            ElNotification({
                                type: "success",
                                title: "成功",
                                message: "《" + this.bookInfo.title + "》信息修改成功",
                            });
                            this.$emit("drawer");
                        })
                        .catch((err) => {
                            console.log(err);
                            // console.log(this.bookInfo);
                            ElNotification({
                                type: "error",
                                title: "修改失败",
                                message: "请联系技术人员",
                            });
                        });
                    this.isLoading = false;
                }
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.image {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 100%;
    justify-content: space-between;

    .el-image {
        margin-left: 2rem;
    }
}
</style>
